package com.cn.lp.jpa.cq.domain;

import com.cn.lp.jpa.cq.CQOrderType;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Root;

public class CQOrder<TFrom> {

    /**
     * 顺序类型
     */
    private CQOrderType type;
    /**
     * 字段
     */
    private CQField field;

    private CQOrder(CQOrderType type, CQField field) {
        this.type = type;
        this.field = field;
    }

    static <TFrom, TSelect> CQOrder<TFrom> of(CQOrderType type, CQField field) {
        return new CQOrder<>(type, field);
    }

    Order toOrder(Root<TFrom> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        switch (type) {
            case ASC:
                return cb.asc(root.get(field.getName()));
            case DESC:
                return cb.desc(root.get(field.getName()));
            default:
                throw new IllegalArgumentException("不支持的类型: " + type.name());
        }
    }

}
